﻿function showErro(msg) {
    if (msg != null && msg.indexOf("发生未知错误") == 0) {
        console.log(msg);
        return;
    }
    if (msg != null && msg != '') {
        console.log(msg);
        api.alert({
            title: '出错啦！',
            msg: msg
        });
    }
}

function showMsg(msg) {
    if (msg != null && msg.indexOf("An error occurred") == 0)
        return;
    if (msg != null && msg != '')
        api.alert({
            title: '提示',
            msg: msg
        });
}

function initialMap() {
    var lyr1 = L.tileLayer.wms(ArcServerUrl + "services/DZHJ/420000vector/MapServer/WMSServer", {
        layers: '0',
        format: 'image/png',
        transparent: true,
        attribution: ""
    });
    var lyr2 = L.tileLayer.wms(ArcServerUrl + "services/DZHJ/420000image/MapServer/WMSServer", {
        layers: '0',
        format: 'image/png',
        transparent: true,
        attribution: ""
    });
    var lyr4 = L.tileLayer.wms(ArcServerUrl + "services/DZHJ/420000JCDZDJ/MapServer/WMSServer", {
        layers: '0,1,2,3,4,5,6',
        format: 'image/png',
        transparent: true,
        attribution: ""
    });
    var lyr5 = L.tileLayer.wms(ArcServerUrl + "services/DZHJ/420000SWDZ/MapServer/WMSServer", {
        layers: '0',
        format: 'image/png',
        transparent: true,
        attribution: ""
    });
    var lyr6 = L.tileLayer.wms(ArcServerUrl + "services/DZHJ/420000GCDZ/MapServer/WMSServer", {
        layers: '0,1',
        format: 'image/png',
        transparent: true,
        attribution: ""
    });
    var baseLayers = {
        "基础地理": lyr1,
        "遥感影像": lyr2
    };
    var overlays = {
        "基础地质": lyr4,
        "水文地质": lyr5,
        "工程地质": lyr6
    };
    var mapOpts = {
        zoomControl: true,
        attributionControl: true
    };
    map = L.map('map', mapOpts).setView([31, 110], 5);
    var lyrOpts = {
        "position": "topright"
    };
    L.control.layers(baseLayers, overlays, lyrOpts).addTo(map);
    lyr1.addTo(map);
}

function initialMap_Debug() {
    var lyr1 = L.tileLayer.wms(ArcServerUrl + "services/SampleWorldCities/MapServer/WMSServer", {
        layers: '0,1,2',
        format: 'image/png',
        transparent: true,
        attribution: ""
    });
    var lyr2 = L.tileLayer.wms(ArcServerUrl + "services/China/MapServer/WMSServer", {
        layers: '0,1,2',
        format: 'image/png',
        transparent: true,
        attribution: ""
    });
    var lyr3 = L.tileLayer.wms(ArcServerUrl + "services/ProjectData/20150606160944/MapServer/WMSServer", {
        layers: '0,1,2',
        format: 'image/png',
        transparent: true,
        attribution: ""
    });
    var lyr4 = L.tileLayer.wms(ArcServerUrl + "services/Geo20W/MapServer/WMSServer", {
        layers: '0,1',
        format: 'image/png',
        transparent: true,
        attribution: ""
    });
    var baseLayers = {
        "世界地图": lyr1,
        "中国地图": lyr2,
        "湖北地图": lyr3
    };
    var overlays = {
        "20万水文地质图": lyr4
    };
    var mapOpts = {
        zoomControl: true,
        attributionControl: true
    };
    map = L.map('map', mapOpts).setView([31, 110], 5);
    var lyrOpts = {
        "position": "topright"
    };
    L.control.layers(baseLayers, overlays, lyrOpts).addTo(map);
    lyr1.addTo(map);
}

function showSaveProgress() {
    api.showProgress({
        style: 'default',
        animationType: 'fade',
        title: '正在保存',
        text: '请稍等...',
        modal: false
    });
}

function getCookie(keyName) {
    var rlt = $api.getStorage(keyName);
    return rlt;
}

function setCookie(keyName, str) {
    $api.setStorage(keyName, str);
}

function request(url, paras) {
    var paraString = url.substring(url.indexOf("?") + 1, url.length).split("&");
    var paraObj = {}
    for (i = 0; j = paraString[i]; i++) {
        paraObj[j.substring(0, j.indexOf("=")).toLowerCase()] = j.substring(j.indexOf("=") + 1, j.length);
    }
    var returnValue = paraObj[paras.toLowerCase()];
    if (typeof(returnValue) == "undefined") {
        return "";
    } else {
        return returnValue.replace("#", "");
    }
}

function Guid(num) {
    if (num == null) {
        num = 1;
    }
    var guidList = null;
    var filter = "num <= " + num + "";
    getRecordsByFilter("prj", "vwGuid", filter, function(res) {
        if (res != null && res.record.length > 0) {
            guidList = [];
            for (var i = 0; i < res.record.length; i++) {
                guidList.push(res.record[i].id);
            }
        }

    }, showErro, false);
    if (num == 1 && guidList != null && guidList.length > 0) {
        return guidList[0];
    }
    return guidList;
}

function Guid2(callback) {
    $.ajax({
            url: ip_req + 'ZHFZ/ZHFZService.svc/GetGUID',
            type: 'get',
            dataType: 'jsonp',
        })
        .done(function(res) {
            callback.call(this, res);
        });

}

function getLocaleDatetime() {
    var objD = new Date();
    var yy = objD.getYear();
    if (yy < 1900)
        yy = yy + 1900;
    var MM = objD.getMonth() + 1;
    if (MM < 10)
        MM = '0' + MM;
    var dd = objD.getDate();
    if (dd < 10)
        dd = '0' + dd;
    var hh = objD.getHours();
    if (hh < 10)
        hh = '0' + hh;
    var mm = objD.getMinutes();
    if (mm < 10)
        mm = '0' + mm;
    var ss = objD.getSeconds();
    if (ss < 10)
        ss = '0' + ss;
    var str = yy + "-" + MM + "-" + dd + " " + hh + ":" + mm + ":" + ss;
    return str;
}

function getLocaleDate() {
    var objD = new Date();
    var yy = objD.getYear();
    if (yy < 1900)
        yy = yy + 1900;
    var MM = objD.getMonth() + 1;
    if (MM < 10)
        MM = '0' + MM;
    var dd = objD.getDate();
    if (dd < 10)
        dd = '0' + dd;
    var str = yy + "-" + MM + "-" + dd;
    return str;
}

function getLocaleTime() {
    var objD = new Date();
    var hh = objD.getHours();
    if (hh < 10)
        hh = '0' + hh;
    var mm = objD.getMinutes();
    if (mm < 10)
        mm = '0' + mm;
    var ss = objD.getSeconds();
    if (ss < 10)
        ss = '0' + ss;
    var str = hh + ":" + mm + ":" + ss;
    return str;
}

function getFormatDate(yy, MM, dd) {
    if (yy < 1900)
        yy = yy + 1900;
    if (MM < 10)
        MM = '0' + MM;
    if (dd < 10)
        dd = '0' + dd;
    var str = yy + "-" + MM + "-" + dd;
    return str;
}

function getFormatTime(hh, mm, ss) {
    if (hh < 10)
        hh = '0' + hh;
    if (mm < 10)
        mm = '0' + mm;
    if (ss < 10)
        ss = '0' + ss;
    var str = hh + ":" + mm + ":" + ss;
    return str;
}

function loginUser(name, pwd) {
    var url = DfServer + 'rest/user/session';
    var data = {
        'email': name + MailSuffix,
        'password': pwd
    };
    var loginState = false;
    $.ajax({
        dataType: 'json',
        contentType: 'application/json;charset=utf-8',
        url: url,
        data: JSON.stringify(data),
        cache: false,
        async: false,
        type: 'POST',
        timeout: 300000,
        headers: {
            "X-DreamFactory-Application-Name": AppName
        },
        success: function(response) {
            setCookie("GEO_USERNAME", name);
            setCookie("GEO_Token", response.session_id);
            setCookie("GEO_User", response.display_name);
            setCookie("display_name", response.display_name);
            setCookie("email", response.email);
            setCookie("first_name", response.first_name);
            setCookie("last_name", response.last_name);
            getPhone();
            loginState = true;
        },
        error: function(response) {
            var msg = "用户密码出错!";
            if (response.content && response.content.data && response.content.data.error)
                msg = response.content.data.error[0].message;
            else if (response.responseText)
                msg = JSON.stringify(response.responseText);
            msg = msg.replace(/&quot;/g, '"').replace(/&gt;/g, '>').replace(/&lt;/g, '<').replace(/&amp;/g, '&').replace(/&apos;/g, '\'');
            showErro(msg);
        }
    });
    return loginState;
}

function loginUser2(name, pwd) {
    var url = DfServer + 'rest/user/session';
    var data = {
        'email': name + MailSuffix,
        'password': pwd
    };
    var loginState = false;
    $.ajax({
        dataType: 'json',
        contentType: 'application/json;charset=utf-8',
        url: url,
        data: JSON.stringify(data),
        cache: false,
        async: false,
        type: 'POST',
        timeout: 300000,
        headers: {
            "X-DreamFactory-Application-Name": AppName
        },
        success: function(response) {
            setCookie("GEO_USERNAME", name);
            setCookie("GEO_Token", response.session_id);
            setCookie("GEO_User", response.display_name);
            setCookie("display_name", response.display_name);
            setCookie("email", response.email);
            setCookie("first_name", response.first_name);
            setCookie("last_name", response.last_name);
            getPhone();
            loginState = true;
        },
        error: function(response) {
            var msg = "用户密码出错!";
            if (response.content && response.content.data && response.content.data.error)
                msg = response.content.data.error[0].message;
            else if (response.responseText)
                msg = JSON.stringify(response.responseText);
            msg = msg.replace(/&quot;/g, '"').replace(/&gt;/g, '>').replace(/&lt;/g, '<').replace(/&amp;/g, '&').replace(/&apos;/g, '\'');
            showErro(msg);
        }
    });
    return loginState;
}

function getPhone() {
    getRecordsByFilter("user", "profile", null, function(res) {
        if (res != null && res.phone != null) {
            setCookie("phone", res.phone);
        }
    }, null, false);
};

function autoLoginUser() {
    var url = DfServer + 'rest/user/session';
    var data = {
        'email': UserName,
        'password': PWD
    };
    var loginState = false;
    $.ajax({
        dataType: 'json',
        contentType: 'application/json;charset=utf-8',
        url: url,
        data: JSON.stringify(data),
        cache: false,
        async: false,
        type: 'GET',
        timeout: 300000,
        headers: {
            "X-DreamFactory-Application-Name": AppName
        },
        success: function(response) {
            setCookie('GEO_USERNAME', UserName);
            setCookie('GEO_Token', response.session_id);
            loginState = true;
        },
        error: function(response) {
            var msg = "用户密码出错!";
            if (response.content && response.content.data && response.content.data.error) {
                msg += "详细信息：" + response.content.data.error[0].message;
            }
            msg = msg.replace(/&quot;/g, '"').replace(/&gt;/g, '>').replace(/&lt;/g, '<').replace(/&amp;/g, '&').replace(/&apos;/g, '\'');
            alert(msg);
        }
    });
    return loginState;
}

function getRecordsByFilter(database, table, filter, success, error, async) {
    var url = DfServer + 'rest/' + database + '/' + table;
    var token = getCookie('GEO_Token');
    var data = null;
    if (filter == null || filter == "" || filter == undefined)
        data = null;
    else
        data = {
            filter: filter
        };
    if (async == null)
        async = false;
    $.ajax({
        dataType: 'json',
        contentType: 'application/json; charset=utf-8',
        url: url,
        data: data,
        cache: false,
        async: async,
        type: 'GET',
        timeout: 300000,
        headers: {
            "X-DreamFactory-Application-Name": AppName,
            "X-DreamFactory-Session-Token": token
        },
        success: function(response) {
            if (typeof success !== 'undefined') {
                success(response);
            }
        },
        error: function(response) {
            console.log(JSON.stringify(response));
            var msg = "发生未知错误";
            if (response.content && response.content.data && response.content.data.error) {
                msg = response.content.data.error[0].message;
            }
            msg = msg.replace(/&quot;/g, '"').replace(/&gt;/g, '>').replace(/&lt;/g, '<').replace(/&amp;/g, '&').replace(/&apos;/g, '\'');
            if (typeof error !== 'undefined' && error) {
                error(msg);
            }
        }
    });
}

function getRecordsByFilterOrder(database, table, filter, order, success, error, async) {
    var url = DfServer + 'rest/' + database + '/' + table;
    var token = getCookie('GEO_Token');
    var data = null;
    if (!filter)
        filter = "";
    data = {
        filter: filter,
        order: order
    };
    if (async == null)
        async = false;
    $.ajax({
        dataType: 'json',
        contentType: 'application/json; charset=utf-8',
        url: url,
        data: data,
        cache: false,
        async: async,
        type: 'GET',
        timeout: 300000,
        headers: {
            "X-DreamFactory-Application-Name": AppName,
            "X-DreamFactory-Session-Token": token
        },
        success: function(response) {
            if (typeof success !== 'undefined') {
                success(response);
            }
        },
        error: function(response) {
            var msg = "发生未知错误";
            if (response.content && response.content.data && response.content.data.error) {
                msg = response.content.data.error[0].message;
            }
            msg = msg.replace(/&quot;/g, '"').replace(/&gt;/g, '>').replace(/&lt;/g, '<').replace(/&amp;/g, '&').replace(/&apos;/g, '\'');
            if (typeof error !== 'undefined') {
                error(msg);
            }
        }
    });
}

function getPageRecordsByFilterOrder(database, table, filter, order, limit, offset, success, error, async) {
    var url = DfServer + 'rest/' + database + '/' + table;
    var token = getCookie('GEO_Token');
    var data = null;
    if (!filter)
        filter = "";
    data = {
        filter: filter,
        order: order,
        include_count: true,
        limit: limit,
        offset: offset
    };
    if (async == null)
        async = false;
    $.ajax({
        dataType: 'json',
        contentType: 'application/json; charset=utf-8',
        url: url,
        data: data,
        cache: false,
        async: async,
        type: 'GET',
        timeout: 300000,
        headers: {
            "X-DreamFactory-Application-Name": AppName,
            "X-DreamFactory-Session-Token": token
        },
        success: function(response) {
            if (typeof success !== 'undefined') {
                success(response);
            }
        },
        error: function(response) {
            console.log(JSON.stringify(response));
            var msg = "发生未知错误";
            if (response.content && response.content.data && response.content.data.error) {
                msg = response.content.data.error[0].message;
            }
            msg = msg.replace(/&quot;/g, '"').replace(/&gt;/g, '>').replace(/&lt;/g, '<').replace(/&amp;/g, '&').replace(/&apos;/g, '\'');
            if (typeof error !== 'undefined') {
                //error(msg);
            }
        }
    });
}

function addRecords(database, table, data, success, error, async) {
    var url = DfServer + 'rest/' + database + '/' + table;
    var token = getCookie('GEO_Token');
    if (data == null || data == "" || typeof data == 'undefined')
        return;
    if (async == null)
        async = false;
    $.ajax({
        dataType: 'json',
        contentType: 'application/json;',
        url: url,
        data: JSON.stringify(data),
        async: async,
        type: 'POST',
        timeout: 300000,
        headers: {
            "X-DreamFactory-Application-Name": AppName,
            "X-DreamFactory-Session-Token": token
        },
        success: function(response) {
            if (typeof success !== 'undefined') {
                success(response);
            }
        },
        error: function(response) {
            console.log(JSON.stringify(response));
            var msg = "发生未知错误";
            if (response.content && response.content.data && response.content.data.error) {
                msg = response.content.data.error[0].message;
            }
            msg = msg.replace(/&quot;/g, '"').replace(/&gt;/g, '>').replace(/&lt;/g, '<').replace(/&amp;/g, '&').replace(/&apos;/g, '\'');
            if (typeof error !== 'undefined') {
                error(msg);
            }
        }
    });
}

function updateRecords(database, table, data, success, error, async) {
    var url = DfServer + 'rest/' + database + '/' + table;
    var token = getCookie('GEO_Token');
    if (data == null || data == "" || typeof data == 'undefined')
        return;
    if (async == null)
        async = false;
    $.ajax({
        dataType: 'json',
        contentType: 'application/json;',
        url: url,
        data: JSON.stringify(data),
        cache: false,
        async: async,
        type: 'PUT',
        timeout: 300000,
        headers: {
            "X-DreamFactory-Application-Name": AppName,
            "X-DreamFactory-Session-Token": token
        },
        success: function(response) {
            if (typeof success !== 'undefined') {
                success(response);
            }
        },
        error: function(response) {
            var msg = "发生未知错误";
            if (response.content && response.content.data && response.content.data.error) {
                msg = response.content.data.error[0].message;
            }
            msg = msg.replace(/&quot;/g, '"').replace(/&gt;/g, '>').replace(/&lt;/g, '<').replace(/&amp;/g, '&').replace(/&apos;/g, '\'');
            if (typeof error !== 'undefined') {
                error(msg);
            }
        }
    });
}

function deleteRecordsByGuid(database, table, filter, success, error, async) {
    var url = DfServer + 'rest/' + database + '/' + table;
    var token = getCookie('GEO_Token');
    if (filter == null || filter == "" || typeof filter == 'undefined')
        return;
    if (async == null)
        async = false;
    var data = {
        filter: filter
    };
    $.ajax({
        dataType: 'json',
        contentType: 'application/json;',
        url: url,
        data: JSON.stringify(data),
        cache: false,
        async: async,
        type: 'DELETE',
        timeout: 300000,
        headers: {
            "X-DreamFactory-Application-Name": AppName,
            "X-DreamFactory-Session-Token": token
        },
        success: function(response) {
            if (typeof success !== 'undefined') {
                success(response);
            }
        },
        error: function(response) {
            var msg = "发生未知错误";
            if (response.content && response.content.data && response.content.data.error) {
                msg = response.content.data.error[0].message;
            }
            msg = msg.replace(/&quot;/g, '"').replace(/&gt;/g, '>').replace(/&lt;/g, '<').replace(/&amp;/g, '&').replace(/&apos;/g, '\'');
            if (typeof error !== 'undefined') {
                error(msg);
            }
        }
    });
}

function getLocaleTimeFileName() {
    var objD = new Date();
    var yy = objD.getYear();
    if (yy < 1900)
        yy = yy + 1900;
    var MM = objD.getMonth() + 1;
    if (MM < 10)
        MM = '0' + MM;
    var dd = objD.getDate();
    if (dd < 10)
        dd = '0' + dd;
    var hh = objD.getHours();
    if (hh < 10)
        hh = '0' + hh;
    var mm = objD.getMinutes();
    if (mm < 10)
        mm = '0' + mm;
    var ss = objD.getSeconds();
    if (ss < 10)
        ss = '0' + ss;
    var str = yy + MM + dd + hh + mm + ss;
    return str;
}

function uploadPictures(pics, belongGuid, modelId) {
    var url = MultimediaUrl + 'page/upload.aspx';
    for (var i = 0; i < pics.length; i++) {
        api.ajax({
            url: url,
            method: 'post',
            timeout: 3000,
            dataType: 'json',
            returnAll: false,
            data: {
                files: {
                    Filedata: pics[i]
                }
            }
        }, function(ret, err) {
            // showMsg('uploadPictures结果:ret:' + JSON.stringify(ret) + '__err:' + JSON.stringify(err));
            if (err && err.statusCode == '200') {
                Guid2(function(guid) {
                    SaveFileBusinessInfo(belongGuid, modelId, err.body, guid);
                });
            }
        });
    }
}

function SaveFileBusinessInfo(belongGuid, modelId, fileName, guid) {
    // showMsg('belongGuid:json:' + (belongGuid)); 
    // showMsg('guid:json:' + (guid)); 
    var typeCode = 'B4183E44-82A9-45E9-A2A5-FCDD8CC12580';
    var index = fileName.lastIndexOf('.');
    var length = fileName.length;
    var ext = 'jpg';
    if (index > 0) {
        ext = fileName.substring(index + 1, length);
    }
    var fullName = getLocaleTimeFileName() + "." + ext;
    var guid = guid;
    var fileInfo = {
        fileTempName: fileName,
        storageMethod: '文件夹',
        description: '',
        fullname: fullName,
        //creator: getCookie('GEO_USERNAME'),
        creator: 'admin',
        guid: guid,
        typeCode: typeCode
    };

    var businessInfo = {
        typeCode: typeCode,
        modelId: modelId,
        belongObjectGuid: belongGuid,
        fileinfoGuid: guid,
    };
    var fileInfoUrl = MultimediaUrl + "AjaxHandler.ashx?class=FileImageInfoAjax&method=addFileImage";
    var businessInfoUrl = MultimediaUrl + "AjaxHandler.ashx?class=BusinessInfoAjax&method=AddBusinessInfo";
    $.ajax({
        url: fileInfoUrl,
        async: false,
        data: fileInfo,
        timeout: 300000,
        success: function(json) { },
        error: function(e) {
            console.log("保存FileImageInfo出错：" + e);
        },
        cache: false
    });
    $.ajax({
        url: businessInfoUrl,
        async: false,
        data: businessInfo,
        timeout: 300000,
        success: function(json) { },
        error: function(e) {
            console.log("保存BusinessInfo出错：" + e);
        },
        cache: false
    });
}

function getServerTime() {
    var time = null;
    //从服务器获取时间
    getRecordsByFilter('qcqf', 'vwTime', null, function(response) {
        if (response.record != null && response.record.length > 0) {
            time = response.record[0].now;
        }
    }, null, false);
    if (time == null) {
        alert("获取服务器时间失败！");
        return null;
    }
    return time;
}

//短信发送
function sendMsg(content, mobiles) {
    if (content == null || content == "" || mobiles == null || mobiles.length < 1)
        return null;
    var rlt = null;
    var url = MsgServerUrl + "AjaxHandler.ashx?class=ShortMsgAjax&method=SendMsg";
    var json = {
        MsgContent: content,
        Mobiles: mobiles
    }
    $.ajax({
        url: url,
        async: false,
        timeout: 300000,
        data: {
            json: JSON.stringify(json)
        },
        success: function(res) {
            rlt = res;
        },
        error: function(e) {
            rlt = e;
        },
        cache: false
    });
    return rlt;
}